package com.leetcode.hot100;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.hot100
 * @Author: lei
 * @CreateTime: 2024-03-21  10:50
 * @Description: 给你一个整数数组 nums 和一个整数 k ，请你统计并返回 该数组中和为 k 的子数组的个数 。
 * 子数组是数组中元素的连续非空序列。
 * @Version: 1.0
 */
public class 和为K的子数组_560 {
    public static void main(String[] args) {
        int[] nums = {28, 54, 7, -70, 22, 65, -6};
        int k = 100;
        System.out.println(subarraySum(nums, k));
    }

   /* public static int subarraySum(int[] nums, int k) {
        int result = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            result += nums[i];
            if (result == k) {
                count++;
            }
            for (int j = i + 1; j < nums.length; j++) {
                result += nums[j];
                if (result == k) {
                    count++;
                }
            }
            result = 0;
        }
        return count;
    }*/

    public static int subarraySum(int[] nums, int k) {
        int[] sumNums = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            sumNums[i + 1] = sumNums[i] + nums[i];
        }
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int num = sumNums[i];
            for (int j = i + 1; j < sumNums.length; j++) {
                int sumNum = sumNums[j];
                if (sumNum - num == k) {
                    count++;
                }
            }
        }
        return count;
    }
}
